﻿using Microsoft.EntityFrameworkCore;
using mozhi.smarterp.Finance.EntityFrameworkCore;
using mozhi.smarterp.Finance.Finances.Repository;
using mozhi.smarterp.Finance.Querys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;

namespace mozhi.smarterp.Finance.Finances
{
    public class JournalNumberPrefixRepository : EfCoreRepository<FinanceDbContext, JournalNumberPrefix,Guid>, IJournalNumberPrefixRepository
    {
        public JournalNumberPrefixRepository(IDbContextProvider<FinanceDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public async Task<List<JournalNumberPrefix>> FindAsync(PageQuery query)
        {
            var dbQuery = DbContext.Set<JournalNumberPrefix>().AsNoTracking();

            var words = await dbQuery.
                WhereIf(query.Id.HasValue, x => x.Id == query.Id).
                WhereIf(!query.Keyword.IsNullOrEmpty(), x => x.Code.Contains(query.Keyword) || x.Name.Contains(query.Keyword)).
                WhereIf(query.ExclusionId.HasValue, x => x.Id != query.ExclusionId)
                .Skip((query.PageIndex - 1) * query.PageSize).Take(query.PageSize)
                .OrderBy(x => x.Code)
                .ToListAsync();

            return words;
        }

        public async Task<JournalNumberPrefix> FindAsync(Guid id, bool includeDetails = true, CancellationToken cancellationToken = default)
        {
            var dbQuery = DbContext.Set<JournalNumberPrefix>().AsNoTracking();

            return await dbQuery.FirstOrDefaultAsync(x => x.Id == id);
        }

        public Task<JournalNumberPrefix> GetAsync(Guid id, bool includeDetails = true, CancellationToken cancellationToken = default)
        {
            var journal = DbContext.Set<JournalNumberPrefix>().FirstOrDefaultAsync(x => x.Id == id);

            return journal;
        }

        public async Task<int> GetCountAsync(PageQuery query)
        {
            var dbQuery = DbContext.Set<JournalNumberPrefix>().AsNoTracking();

            var count = await dbQuery.
                WhereIf(query.Id.HasValue, x => x.Id == query.Id).
                WhereIf(query.ExclusionId.HasValue, x => x.Id != query.ExclusionId).
                WhereIf(!query.Keyword.IsNullOrEmpty(), x => x.Name != null && x.Name.Contains(query.Keyword))
                .CountAsync();

            return count;
        }
    }
}
